#!/usr/bin/env python
# -*- coding: utf-8 -*-

from IL.Socket.Singleton import singleton
from threading import RLock

@singleton
class MarketSource:
    def __init__(self):
        self.market_lock = RLock()
        self.codeTable_lock = RLock()
        self.codeTable = dict()
        self.market = dict()
        self.idToCode = dict()

    def get(self, code):
        code = self.codeTable.get(code, None)
        if code is None:
            return None
        self.market_lock.acquire()
        ret = self.market.get(code.idnum, None)
        self.market_lock.release()
        return ret

    def set(self, code, market):
        self.market_lock.acquire()
        self.market[code] = market
        self.market_lock.release()

    def setCodeInfo(self, code, data):
        self.codeTable_lock.acquire()
        self.codeTable[code] = data
        self.idToCode[data.idnum] = code
        self.codeTable_lock.release()

    def get_code_by_id(self, idnum):
        return self.idToCode.get(idnum, None)

    def getCodeInfo(self, code):
        self.codeTable_lock.acquire()
        ret = self.codeTable.get(code, None)
        self.codeTable_lock.release()
        return ret

    def getStockCodeIsSH(self, code):
        self.codeTable_lock.acquire()
        ret = self.codeTable.get(code, None)
        self.codeTable_lock.release()
        if ret:
            if ret.idnum % 100 == 1:
                return 1
            else:
                return 0
        return 0

    def getStockCodelist(self):
        return list(self.codeTable.keys())

if __name__ == u'__main__':
    pass